// 图片
let fs = require('fs');
let path = require('path');
let images = require('images');
let errinfo = require('../errinfo.js');
let responseJsonUtils = require('../utils/responseJsonUtils.js');
let uploadUtils = require('../utils/uploadUtils');
let picUtils = require('../utils/picUtils');

let picBusiness = module.exports = {};

/**
 * parameter name
 */
picBusiness.paramName = function (req, res, next, name) {
    let nameArray = name.split('.');

    if (nameArray.length !== 2) {
        next(responseJsonUtils.json(errinfo.pic.notFount, 404));
        return;
    }
    req.name = nameArray[0];
    req.ext = nameArray[1];
    req.filePath = path.resolve(appRoot, uploadUtils.destination + '/' + req.params.name);
    next();
};

/**
 *  get pic
 */
// check file exist
picBusiness.checkFileExist = function (req, res, next) {
    fs.exists(req.filePath, function (exist) {
        if (!exist) {
            next(responseJsonUtils.json(errinfo.pic.notFount, 404));
            return;
        }
        req.image = images(req.filePath);
        next();
    });
};


// check file exist
picBusiness.zoom = function (req, res, next) {
    let buffer;
    if (req.query.slim) {
        // slim the pic
        req.image.resize(500);
    }
    buffer = req.image.encode('jpg')
    // req.image.resize()
    res.writeHead(200, {'Content-Type': 'image/jpeg'});    //写http头部信息
    res.end(buffer, 'binary');
};

